#include "admin.h"

static bool adminLogin(string adminPass, SOCKET clientSocket);
static void adminMenu(u_short httpPort, SOCKET clientSocket);
static void startServer(u_short httpPort);

void admin(SOCKET clientSocket){
	char *buffer;
	
	webConfigDataStruct configData;

	//configData = New(configDataT);
	configData = getConfigData();
	
	buffer = "Enter password: ";

	while (TRUE){
		send(clientSocket, buffer, strlen(buffer), 0);
		if (adminLogin(configData.password, clientSocket)){
			adminMenu(configData.httpPort, clientSocket);
			//free(configData);
			break;
		}
	}
}

static bool adminLogin(string adminPass, SOCKET clientSocket){
	int i = 0;
	string pass;
	char c;
	
	pass = "";

	while (TRUE){

		while (TRUE){
			recv(clientSocket, &c, 1, 0);
			if (isalpha(c) || isdigit(c) || c == 13) break;
		}

		if (c == 13){ 
			pass[i] = '\0';
			break;
		} else {
			pass = Concat(pass, CharToString(c));
			i++;
		}
	}

	if (StringEqual(pass, adminPass)){
		return TRUE;
	} else {
		return FALSE;
	}
}

static void adminMenu(u_short httpPort, SOCKET clientSocket){
	char choice;
	char *buffer;

	buffer = "\r\n1. Start server\r\n2. Stop sever\r\n3. Logg\r\n0. Quit\r\n";
	while (TRUE){	

		send(clientSocket, buffer, strlen(buffer), 0);
		
		while (TRUE) {
			recv(clientSocket, &choice, 1, 0);
			if (isdigit(choice)) break;
		}

		switch(choice){
			case '1':	startServer(httpPort);
						send(clientSocket, "\r\nServer started", 18, 0);
						break;
			case '2':	webbStop();
						send(clientSocket, "\r\nServer stopped", 18, 0);
						break;
			case '3':	sendLogToSocket(&clientSocket);
						break;
			case '0':	return;
			default:	send(clientSocket, "\r\nWrong Input", 15, 0);
						break;
		}
	}
}

static void startServer(u_short httpPort){
	
	if(!isWebRunning()){
		if(webbStart(httpPort) == NULL){
			printf("Error on admin starting web server...\n");
			return;
		}
	}
}
